package com.wsx.rpc.metrics.health;

import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;

import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * @author wangshuaixin
 * @Title: com.wsx.rpc.metrics.health.DatabaseHealthCheck
 * @Description: TODO
 * @date 2018/11/28
 */
public class DatabaseHealthCheck extends HealthCheck {

    private final Database database;

    public DatabaseHealthCheck(Database database) {
        this.database = database;
    }

    @Override
    protected Result check() throws Exception {
        if (database.ping()) {
            return Result.healthy();
        }
        return Result.unhealthy("can ping database");
    }

    static class Database {

        public boolean ping() {
            Random random = new Random();
            return random.nextBoolean();
        }
    }


    public static void main(String[] args) {
        HealthCheckRegistry registry = new HealthCheckRegistry();
        registry.register("database1", new DatabaseHealthCheck(new Database()));
        registry.register("database2", new DatabaseHealthCheck(new Database()));

        while (true) {
            Set<Map.Entry<String, Result>> set = registry.runHealthChecks().entrySet();
            for (Map.Entry<String, Result> entry : set) {
                if (entry.getValue().isHealthy()) {
                    System.out.println(entry.getKey() + ": OK");
                } else {
                    System.err.println(entry.getKey() + ": FAIL, error message: " + entry.getValue().getMessage());
                    final Throwable e = entry.getValue().getError();
                    if (e != null) {
                        e.printStackTrace();
                    }
                }
            }

            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
